# https://kkembed.kdwshell.com/embed/73519
# https://www.jianshu.com/p/331aa20937ba
import os
import random
import time


import requests
from tqdm import tqdm


def download(video_url, v_id):
    headers = {
        'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9'
        , 'Accept-Encoding': 'gzip, deflate, br'
        , 'Accept-Language': 'en,zh-CN;q=0.9,zh;q=0.8'
        , 'Cache-Control': 'max-age=0'
        , 'Connection': 'keep-alive'
        , 'Range': 'bytes=0-600'
        , 'Sec-Fetch-Dest': 'document'
        , 'Sec-Fetch-Mode': 'navigate'
        , 'Sec-Fetch-Site': 'none'
        , 'Sec-Fetch-User': '?1'
        , 'Upgrade-Insecure-Requests': '1'
        ,
        'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/81.0.4044.129 Safari/537.36'
    }

    r = requests.get(video_url, headers=headers)
    v_url = r.url
    print(v_url)
    headers_v = {
        'Accept': '*/*',
        'Accept-Encoding': 'identity;q=1, *;q=0',
        'Accept-Language': 'en,zh-CN;q=0   .9,zh;q=0.8',
        'Cache-Control': 'max-age=0',
        'Connection': 'keep-alive',
        'Range': 'bytes=0-',
        'Sec-Fetch-Dest': 'video',
        'Sec-Fetch-Mode': 'no-cors',
        'Sec-Fetch-Site': 'same-origin',
        'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/81.0.4044.129 Safari/537.36',
        'Referer': v_url
                 }
    dst = '/tmp/' + str(v_id) + '.mp4'
    result = requests.get(v_url, headers=headers_v, stream=True)
    file_size = int(result.headers['content-length'])
    pbar = tqdm(total=file_size, initial=0,
                unit='B', unit_scale=True, desc=dst)
    with open(dst, "wb") as mp4:
        for chunk in result.iter_content(chunk_size=1024):
            if chunk:
                mp4.write(chunk)
                pbar.update(1024)

    print("下载结束")
    pbar.close()


def download_from_url(url, dst):
    response = requests.get(url, stream=True) #(1)
    file_size = int(response.headers['content-length']) #(2)
    if os.path.exists(dst):
        first_byte = os.path.getsize(dst) #(3)
    else:
        first_byte = 0
    if first_byte >= file_size: #(4)
        return file_size
    header = {"Range": f"bytes={first_byte}-{file_size}"}
    pbar = tqdm(total=file_size, initial=first_byte,
        unit='B', unit_scale=True, desc=dst)
    req = requests.get(url, headers=header, stream=True) #(5)
    with(open(dst, 'ab')) as f:
        for chunk in req.iter_content(chunk_size=1024): #(6)
            if chunk:
                f.write(chunk)
                pbar.update(1024)
    pbar.close()
    return file_size


def main():
    url_origin = "https://kkembed.kdwshell.com/embed/"
    headers = {
        'accept-encoding': 'gzip, deflate, br'
        ,
        'accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9'
        , 'accept-language': 'en,zh-CN;q=0.9,zh;q=0.8'
        , 'cache-control': 'max-age=0'
        , 'sec-fetch-dest': 'document'
        , 'sec-fetch-mode': 'navigate'
        , 'sec-fetch-site': 'none'
        , 'sec-fetch-user': '?1'
        , 'upgrade-insecure-requests': '1'
        ,
        'user-agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/81.0.4044.129 Safari/537.36'

    }
    list_num = []
    start = 74100
    for i in range(100):
        list_num.append(start + i)
    random.shuffle(list_num)
    v_list = []
    for item in list_num:

        url = url_origin + str(item)
        # print(url)

        try:
            result = requests.get(url, headers=headers)
            html_text = result.text
            start = html_text.index('rnd')
            end = html_text.index('video_url')
            # print(start, end)
            rnd = (html_text[start + 6: end - 12])
            start = end
            end = html_text.index('postfix')
            video_url = (html_text[start + 12:end - 12])
            video_url = video_url + '&rnd=' + rnd
            print(video_url)
            # # download(video_url, item)
            # time.sleep(random.randint(3, 10))
            v_list.append(video_url)
        except Exception as e:
            print(e, item)

    # print(v_list)


if __name__ == '__main__':
    main()
